ssh.bash

#!/usr/bin/env bash

import core/ssh-setup

##
#
# @tip ssh things
function ssh(){
    run help "ssh"
}

##
# Configure which ssh private key file to use
#
function ssh_which(){
    prompt_or_quit "Enter path to private ssh-key file to use for current repo." sshKeyPath \
        || return;

    git config core.sshCommand "ssh -i $sshKeyPath -F /dev/null"
}

##
# Add an ssh key to authentication agent
#
# @tip Add SSH key to authentication agent
function ssh_add(){

    #@TODO set path to ssh dir via a config
    dir="$1"
    if [[ -z "$1" ]];then
        dir="~/.ssh"
        dir=$(expand_tilde_path "$dir")
    fi

    dir=$(remove_trail_slash "$dir")/

    header "Setup ssh keys to upload/download your files"
    msg
    
    if [[ -n "$dir" ]]; then
        msg_instruct "[enter] to use ${dir} or"
    fi
    prompt_or_quit "Enter ssh-keys directory: " promptDir -e\
        || return;

    if [[ -n "$promptDir" ]];then
        dir=$(expand_tilde_path "$promptDir")
    elif [[ -z "$dir" ]]; then
        #@TODO also check if directory exists
        msg_mistake "no directory was given"
        return;
    fi

    msg
    dir=$(remove_trail_slash "$dir")

    declare -a keyfiles
    cmd="prompt_choose choice \\\\\n \"# SSH Key Files\" \"'Which key file would you like to unlock?\" \\\\\n"
    for entry in "$dir"/*
    do
        if [[ -f "$entry" && "${entry:(-4)}" != ".pub" ]]; then
            len=$(str_len "${dir}/")
            file="${entry:$len}"
            if [[ "$file" == "known_hosts" ]];then
                continue 
            fi
            cmd+="\"${file}\" \"${file}\" \"${file}\" \\\\\n"
        fi
    done
    cmd+=";"
    cmd="$(msg "$cmd")"
    eval "${cmd}"

    if [[ -z "${choice}" ]]; then
        return
    fi
    file="${dir}/${choice}"
    sig="$(ssh-keygen -l -f "${file}")"
    keysAdded=( "$(ssh-add -l)" )
    success="false"
    while read line; do
        if [[ "$line" == "$sig" ]];then
            success="true";
            msg
            msg_success "Key has already been added"
            break 2
        fi
    done < <(echo "$keysAdded")
    # echo "$success"
    if [[ "$success" == "false" ]]; then
        ssh-add "${file}"
        # msg
    fi


}